<!--
 * @Description: file content
 * @Author: oooh
 * @Date: 2024-04-26 11:16:35
 * @LastEditors: oooh
 * @LastEditTime: 2024-08-07 18:08:39
 * @FilePath: \Civil_Servant_Performance_PC\src\views\work-approval\assessment-grades\index.vue
-->
<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner" style="flex-shrink: 0">
      <span>站办所绩效管理考评等次</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <div class="flex justify-between" v-hasPermi="['approval:assessment-grades:submit']">
      <div>
        <span style="font-size: 14px">批量设定：</span>
        <el-button
          size="mini"
          type="primary"
          plain
          :disabled="work.submitMark || !selectionList.length"
          v-show="checkBtnVisible('submit')"
          @click="handleGrade(item)"
          v-for="item in dict.type.biz_work_grade"
          :key="item.value"
          >{{ item.label }}</el-button
        >
      </div>
      <div>
        <ApprovalLog :biz-id="work.auditLog.bizId" placement="bottom-end">
          <el-button
            icon="el-icon-s-claim"
            size="mini"
            type="primary"
            plain
            :disabled="!tableList.length || work.submitMark"
            v-show="checkBtnVisible('submit')"
            @click="handleSaveOrSubmit('submit')"
            >提交</el-button
          >
        </ApprovalLog>
        <el-button
          class="ml-10"
          icon="el-icon-s-claim"
          size="mini"
          type="warning"
          plain
          :disabled="!tableList.length || work.submitMark"
          v-show="checkBtnVisible('save')"
          @click="handleSaveOrSubmit('save')"
          >保存</el-button
        >
      </div>
    </div>
    <div class="float-right mb-10">
      <ApprovalLog :biz-id="work.auditLog.bizId" v-hasPermi="['approval:assessment-grades:pass']">
        <el-button
          icon="el-icon-s-claim"
          size="mini"
          type="primary"
          plain
          :disabled="!tableList.length || work.auditLog.auditStatusDict !== 'DSH'"
          @click="handleApproval('pass')"
          >审批通过</el-button
        >
      </ApprovalLog>
      <ApprovalLog :biz-id="work.auditLog.bizId" v-hasPermi="['approval:assessment-grades:reject']">
        <el-button
          class="ml-10"
          icon="el-icon-s-release"
          size="mini"
          type="danger"
          plain
          :disabled="!tableList.length || work.auditLog.auditStatusDict !== 'DSH'"
          @click="handleApproval('reject')"
          >审批退回</el-button
        >
      </ApprovalLog>
    </div>
    <div class="table">
      <el-table
        :data="tableList"
        border
        style="width: 100%"
        height="100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        header-cell-class-name="table-header"
      >
        <el-table-column type="selection" :selectable="checkSelectable"> </el-table-column>
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="站办所" align="center"> </el-table-column>
        <el-table-column v-for="(item, index) in columns" :key="item.label" :label="item.label" prop="total" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.detailsJson[index].score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" align="center"> </el-table-column>

        <el-table-column prop="rank" label="全镇排名" align="center" v-if="hasPermi('approval:cadre-assessment-grades:view-ranking')">
        </el-table-column>
        <el-table-column prop="rank" label="全镇排名" align="center" v-if="hasPermi('approval:cadre-assessment-grades:view-ranking-range')">
          <template slot-scope="scope">
            <span>{{ formatRankingRange(scope.row.rank) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gradeDict" label="考评等次" width="180" align="center">
          <template slot-scope="scope">
            <el-select v-if="!work.submitMark" v-model="scope.row.gradeDict" placeholder="选择考评等次">
              <el-option v-for="item in dict.type.biz_work_grade" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
            <dict-tag v-else :options="dict.type.biz_work_grade" :value="scope.row.gradeDict"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="180" align="center">
          <template slot-scope="scope">
            <span class="pre-wrap align-left">{{ scope.row.remarks || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { list, rating as listSubmit, approval } from '@/api/work-approval/assessment-grades'
import { quarterFormat } from '@/utils/quarter.js'
import ApprovalLog from '@/components/ApprovalLog'
import { getConfigKey } from '@/api/system/config'

export default {
  name: 'assessment-grades',
  dicts: ['biz_work_year_list', 'biz_work_grade'],
  components: { ApprovalLog },
  data() {
    return {
      columns: [],
      loading: false,
      quarterOptions: [],
      tableList: [],
      work: {},
      queryParams: {
        year: '',
        quarter: ''
      },
      selectionList: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getConfigKey()
    this.handleYearChange(new Date().getFullYear())
  },
  methods: {
    getConfigKey() {
      getConfigKey('sys.performanceGrade.rankInterval').then(res => {
        this.rankingRange = res.msg || 0
      })
    },
    // 排名范围格式
    formatRankingRange(ranking) {
      let range = '-'
      if (!this.rankingRange || this.rankingRange === 0) {
        return range
      }
      if (ranking <= this.rankingRange) {
        range = `1-${this.rankingRange}`
      } else {
        while (ranking % this.rankingRange !== 0) {
          ranking++
        }
        range = `${ranking - this.rankingRange + 1}-${ranking}`
      }
      return range
    },
    hasPermi(permi) {
      return this.$auth.hasPermi(permi)
    },
    handleGrade(raw) {
      for (let item of this.selectionList) {
        let index = this.tableList.findIndex(tableItem => tableItem == item)
        this.$set(this.tableList[index], 'gradeDict', raw.value)
      }
    },
    // 校验表格是否可选
    checkSelectable(raw, index) {
      return !this.work.submitMark
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    checkBtnVisible(operation) {
      switch (operation) {
        case 'save':
        case 'submit':
        case 'pass':
        case 'reject':
          return this.work.auditLog.auditStatusDict !== 'SHTG'
        case 'finish':
          return this.work.auditLog.auditStatusDict === 'SHTG'
        default:
          break
      }
    },
    // 审批
    handleApproval(operation) {
      let params = { ...this.queryParams, auditStatusDict: 'SHTG', auditRemark: '同意' }
      if (operation === 'reject') {
        params.auditStatusDict = 'SHBTG'
        params.auditRemark = '不同意'
      }
      let content = `请输入审批意见`
      this.approvalPrompt(operation, content, params.auditRemark, params)
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, '审批提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入审批意见',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: '审批意见不能为空',
        beforeClose: (action, instance, done) => {
          params.auditRemark = instance.inputValue
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '数据处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            approval(params)
              .then(() => {
                loading.close()
                if (operation === 'pass') {
                  this.$modal.msgSuccess('已通过')
                } else if (operation === 'reject') {
                  this.$modal.msgError('已退回')
                }
                this.handleRefresh()
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    handleSaveOrSubmit(operation) {
      let submitMark = false
      if (operation === 'submit') submitMark = true
      let quarterScoreRatingList = this.tableList.map(item => {
        return { id: item.id, gradeDict: item.gradeDict }
      })
      let params = { submitMark, quarterScoreRatingList }
      listSubmit(params).then(res => {
        if (operation === 'submit') {
          this.$modal.msgSuccess('已提交')
        } else if (operation === 'save') {
          this.$modal.msgSuccess('已保存')
        }
        this.handleRefresh()
      })
    },
    async getList() {
      this.loading = true
      list(this.queryParams)
        .then(res => {
          this.loading = false
          this.work = res.data
          let hasRole = this.$auth.hasRole('leadershipGroup')
          if (hasRole) {
            this.tableList = res.data.submitMark ? res.data.bizList : []
          } else {
            this.tableList = res.data.bizList
          }
          this.columns = res.data.bizList[0]['detailsJson'].map(item => {
            return { label: item.label, value: item.score }
          })
        })
        .catch(err => (this.loading = false))
    },
    // 刷新
    handleRefresh() {
      this.getList()
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.$nextTick(() => {
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input-number--medium {
  width: auto;
}
::v-deep .table-header .cell {
  white-space: pre-wrap;
}
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .table {
    flex: 1;
    overflow-y: hidden;
  }
}
</style>
